<template>
  <div class="order-confirm">
    <!-- 地址信息部分 -->
    <div class="address-info">
      <h3><i class="iconfont icon-dizhi"></i>收货地址</h3>
      <div v-if="selectedAddress" class="address-card" @click="showAddressList = true">
        <div class="address-header">
          <span class="address-name">{{ selectedAddress.name }}</span>
          <span class="address-tag" v-if="selectedAddress.otherName">{{ selectedAddress.otherName }}</span>
          <span v-if="selectedAddress.isDefault === 1" class="default-tag">默认</span>
        </div>
        <div class="address-phone">{{ selectedAddress.phone }}</div>
        <div class="address-detail">{{ selectedAddress.area }}</div>
        <span class="change-address">点击切换地址</span>
      </div>
      <div v-else class="no-address" @click="showAddressList = true">
        <i class="iconfont icon-tianjiadizhi"></i>暂无收货地址，点击选择
      </div>

      <!-- 地址选择弹窗 -->
      <div v-if="showAddressList" class="address-list-modal">
        <div class="modal-mask" @click="showAddressList = false"></div>
        <div class="modal-container">
          <div class="modal-header">
            <h3>选择收货地址</h3>
            <span class="close-modal" @click="showAddressList = false">×</span>
          </div>
          <div class="modal-body">
            <div
              v-for="address in addressList"
              :key="address.id"
              :class="['address-item', { active: selectedAddress?.id === address.id }]"
              @click="selectAddress(address)"
            >
              <div class="address-header">
                <span class="address-name">{{ address.name }}</span>
                <span class="address-tag" v-if="address.otherName">{{ address.otherName }}</span>
                <span v-if="address.isDefault === 1" class="default-tag">默认</span>
              </div>
              <div class="address-phone">{{ address.phone }}</div>
              <div class="address-detail">{{ address.area }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 商品信息部分 -->
    <div class="product-list">
      <h3><i class="iconfont icon-shangpin"></i>商品信息</h3>
      <div class="product-item" v-for="item in products" :key="item.prodId">
        <div class="product-img">
          <img :src="item.prodImg || defaultProductImg" alt="商品图片" />
        </div>
        <div class="product-info">
          <div class="product-title">{{ item.prodName }}</div>
          <div class="product-meta">
            <span class="product-price">单价：¥{{ item.prodPrice.toFixed(2) }}</span>
            <span class="product-quantity">数量：x{{ item.prodNum }}</span>
            <span class="product-total">小计：¥{{ (item.prodPrice * item.prodNum).toFixed(2) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 优惠券部分 -->
    <div class="coupon-info">
      <h3><i class="iconfont icon-youhuiquan"></i>优惠券</h3>
      <div class="coupon-select-container">
        <select v-model="selectedCouponId" class="coupon-select">
          <option value="">不使用优惠券</option>
          <option
            v-for="coupon in validCoupons"
            :key="coupon.bagId"
            :value="coupon.bagId"
            :disabled="coupon.disabled"
          >
            {{ formatCouponOption(coupon) }}
          </option>
        </select>
        <i class="iconfont icon-xiala"></i>
      </div>
      
      <div class="coupon-tip" v-if="selectedCoupon">
        已选择优惠券：{{ selectedCoupon.name }}（减¥{{ selectedCoupon.value }}）
      </div>
      
      <div class="coupon-list-container">
        <div class="coupon-list">
          <div
            v-for="coupon in validCoupons"
            :key="coupon.bagId"
            :class="['coupon-card', { 
              active: coupon.bagId === selectedCouponId,
              disabled: coupon.disabled
            }]"
            @click="toggleCoupon(coupon)"
          >
            <div class="coupon-value-box">
              <span class="currency-symbol">¥</span>
              <span class="coupon-value">{{ coupon.value }}</span>
            </div>
            <div class="coupon-detail">
              <div class="coupon-name">{{ coupon.name }}</div>
              <div class="coupon-condition">
                {{ coupon.userLimitValue > 0 ? `满${coupon.userLimitValue}可用` : '无门槛' }}
              </div>
              <div class="coupon-expire">有效期至：{{ formatDate(coupon.expireTime) }}</div>
            </div>
            <div class="coupon-status" v-if="coupon.disabled">
              不满足使用条件
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 订单汇总 -->
    <div class="order-summary">
      <div class="summary-details">
        <div class="summary-row">
          <span>商品总价：</span>
          <span>¥{{ subtotal.toFixed(2) }}</span>
        </div>
        <div class="summary-row" v-if="selectedCoupon">
          <span>优惠券抵扣：</span>
          <span class="discount">-¥{{ selectedCoupon.value.toFixed(2) }}</span>
        </div>
        <div class="summary-row">
          <span>运费：</span>
          <span>¥{{ shippingFee.toFixed(2) }}</span>
        </div>
      </div>
      <div class="total">
        <span>实付款：</span>
        <span class="total-amount">¥{{ totalAmount.toFixed(2) }}</span>
      </div>
      <button class="submit-btn" @click="submitOrder">
        <i class="iconfont icon-zhifu"></i>提交订单
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import request from '@/api/request.js'

const router = useRouter()
const route = useRoute()

// 默认商品图片
const defaultProductImg = 'https://api.iconify.design/mdi:package-variant-closed.svg?color=%23f23030&width=60&height=60'

// 商品数据
const products = ref(route.query?.prods || [])

// 地址数据
const addressList = ref([])
const selectedAddress = ref(null)
const showAddressList = ref(false)

// 优惠券数据
const coupons = ref([])
const selectedCouponId = ref('')

// 价格相关
const subtotal = computed(() => {
  return products.value.reduce((sum, item) => sum + item.prodPrice * item.prodNum, 0)
})
const shippingFee = ref(0) // 运费
const totalAmount = computed(() => {
  let amount = subtotal.value + shippingFee.value
  if (selectedCoupon.value && subtotal.value >= selectedCoupon.value.userLimitValue) {
    amount -= selectedCoupon.value.value
  }
  return amount > 0 ? amount : 0
})

// 获取地址列表
const getAddressList = async () => {
  try {
    const response = await request.post('/address/page', {
      pageNo: 1,
      pageSize: 10
    })
    
    if (response.code === 200) {
      addressList.value = response.data.records
      // 设置默认选中地址（优先选默认地址，没有则选第一个）
      selectedAddress.value = addressList.value.find(addr => addr.isDefault === 1) || addressList.value[0]
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
  }
}

// 选择地址
const selectAddress = (address) => {
  selectedAddress.value = address
  showAddressList.value = false
}

// 获取优惠券列表
const getCouponList = async () => {
  try {
    const response = await request.post('/bag/my/quan', {
      pageNum: 1,
      pageSize: 50
    })
    
    if (response && response.quanVOs) {
      coupons.value = response.quanVOs.map(quan => ({
        ...quan,
        disabled: quan.userLimitValue > 0 && subtotal.value < quan.userLimitValue
      }))
    }
  } catch (error) {
    console.error('获取优惠券列表失败:', error)
  }
}

// 计算可用的优惠券
const validCoupons = computed(() => {
  return coupons.value.filter(coupon => !coupon.expire)
})

// 当前选中的优惠券
const selectedCoupon = computed(() => {
  return coupons.value.find(c => c.bagId === selectedCouponId.value)
})

// 切换优惠券
const toggleCoupon = (coupon) => {
  if (coupon.disabled) return
  selectedCouponId.value = selectedCouponId.value === coupon.bagId ? '' : coupon.bagId
}

// 格式化优惠券选项
const formatCouponOption = (coupon) => {
  let text = coupon.name
  if (coupon.userLimitValue > 0) {
    text += ` (满${coupon.userLimitValue}减${coupon.value})`
  } else {
    text += ` (无门槛减${coupon.value})`
  }
  return text
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const d = new Date(dateStr)
  return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`
}

// 提交订单
const submitOrder = async () => {
  if (!selectedAddress.value) {
    alert('请选择收货地址')
    return
  }

  try {
    const productIds = products.value.map(item => item.prodId)
    const numbers = products.value.map(item => item.prodNum)
    
    const response = await request.post('/order/create', {
      productIds,
      numbers,
      addressId: selectedAddress.value.id,
      bagId: selectedCoupon.value?.bagId || null,
      isShoppingCart: true
    })
    
    if (response.data.code === 200) {
      router.push({
        path: '/pay',
        query: {
          orderId: response.data.id,
        }
      })
    } else {
      alert(response.data.message || '提交订单失败')
    }
  } catch (error) {
    console.error('提交订单失败:', error)
    alert('提交订单失败，请重试')
  }
}

// 初始化数据
onMounted(async () => {


  await Promise.all([getAddressList(), getCouponList()])
})

// 监听商品总价变化，更新优惠券可用状态
watch(subtotal, (newVal) => {
  coupons.value = coupons.value.map(coupon => ({
    ...coupon,
    disabled: coupon.userLimitValue > 0 && newVal < coupon.userLimitValue
  }))
})
</script>

<style scoped>
/* 基础样式 */
.order-confirm {
  max-width: 820px;
  margin: 20px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

/* 各部分标题样式 */
.address-info h3,
.product-list h3,
.coupon-info h3 {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
  display: flex;
  align-items: center;
}

.iconfont {
  margin-right: 8px;
  font-size: 18px;
  color: #f23030;
}

/* 地址卡片样式 */
.address-card {
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 8px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.2s;
  background-color: #fafafa;
}

.address-card:hover {
  border-color: #f23030;
  box-shadow: 0 2px 8px rgba(242, 48, 48, 0.1);
}

.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.address-name {
  font-weight: bold;
  margin-right: 10px;
}

.address-tag {
  padding: 2px 6px;
  background-color: #f0f0f0;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
  margin-right: 8px;
}

.default-tag {
  padding: 2px 6px;
  background-color: #f23030;
  color: white;
  border-radius: 4px;
  font-size: 12px;
}

.address-phone {
  color: #666;
  margin-bottom: 5px;
}

.address-detail {
  color: #333;
  margin-bottom: 5px;
}

.change-address {
  display: inline-block;
  margin-top: 8px;
  color: #f23030;
  font-size: 13px;
}

.no-address {
  padding: 15px;
  text-align: center;
  border: 1px dashed #ccc;
  border-radius: 8px;
  color: #999;
  cursor: pointer;
  transition: all 0.2s;
}

.no-address:hover {
  border-color: #f23030;
  color: #f23030;
}

/* 地址选择弹窗 */
.address-list-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-container {
  position: relative;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.2);
}

.modal-header {
  padding: 15px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
}

.close-modal {
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.close-modal:hover {
  color: #333;
}

.modal-body {
  padding: 15px;
  max-height: calc(80vh - 100px);
  overflow-y: auto;
}

.address-item {
  padding: 12px;
  border: 1px solid #eee;
  border-radius: 6px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.2s;
}

.address-item:hover {
  border-color: #f23030;
}

.address-item.active {
  border-color: #f23030;
  background-color: #fff6f6;
}

/* 商品列表样式 */
.product-item {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.product-item:last-child {
  border-bottom: none;
}

.product-img {
  width: 80px;
  height: 80px;
  margin-right: 15px;
}

.product-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

.product-info {
  flex: 1;
}

.product-title {
  font-size: 15px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
}

.product-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  font-size: 13px;
  color: #666;
}

.product-price,
.product-quantity,
.product-total {
  white-space: nowrap;
}

.product-total {
  color: #f23030;
  font-weight: bold;
}

/* 优惠券选择样式 */
.coupon-select-container {
  position: relative;
  margin-bottom: 15px;
}

.coupon-select {
  width: 100%;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  appearance: none;
  background-color: #fff;
  font-size: 14px;
  cursor: pointer;
}

.coupon-select:focus {
  border-color: #f23030;
  outline: none;
}

.icon-xiala {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  pointer-events: none;
}

.coupon-tip {
  font-size: 13px;
  color: #f23030;
  margin-bottom: 10px;
}

.coupon-list-container {
  max-height: 300px;
  overflow-y: auto;
}

.coupon-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 12px;
}

.coupon-card {
  position: relative;
  display: flex;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.2s;
  background-color: #fff;
}

.coupon-card:hover {
  border-color: #f23030;
}

.coupon-card.active {
  border-color: #f23030;
  background-color: #fff6f6;
}

.coupon-card.disabled {
  opacity: 0.6;
  cursor: not-allowed;
  background-color: #f9f9f9;
}

.coupon-value-box {
  min-width: 60px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #fff0f0;
  border-radius: 6px;
  padding: 8px;
  margin-right: 12px;
}

.currency-symbol {
  font-size: 14px;
  color: #f23030;
}

.coupon-value {
  font-size: 20px;
  font-weight: bold;
  color: #f23030;
}

.coupon-detail {
  flex: 1;
}

.coupon-name {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 4px;
  color: #333;
}

.coupon-condition {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.coupon-expire {
  font-size: 11px;
  color: #999;
}

.coupon-status {
  position: absolute;
  right: 10px;
  top: 10px;
  font-size: 11px;
  color: #f23030;
}

/* 订单汇总样式 */
.order-summary {
  margin-top: 20px;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.summary-details {
  margin-bottom: 15px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.discount {
  color: #f23030;
}

.total {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
  border-top: 1px solid #eee;
  font-size: 16px;
  font-weight: bold;
}

.total-amount {
  font-size: 20px;
  color: #f23030;
}

.submit-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding: 12px;
  margin-top: 15px;
  background-color: #f23030;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.2s;
}

.submit-btn:hover {
  background-color: #e61a1a;
}

.submit-btn .iconfont {
  margin-right: 8px;
  color: white;
  font-size: 16px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .order-confirm {
    padding: 15px;
  }
  
  .coupon-list {
    grid-template-columns: 1fr;
  }
}
</style>